/*
 * @lc app=leetcode.cn id=39 lang=java
 *
 * [39] 组合总和
 */

// @lc code=start

import java.util.ArrayList;
import java.util.List;
import java.util.LinkedList;
import java.util.*;

class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        Arrays.sort(candidates);
        backTracking(candidates, target, 0, 0);
        return res;
    }

    List<List<Integer>> res = new ArrayList<>();
    List<Integer> path = new LinkedList<>();
    private void backTracking(int[] candidates, int target, int sum, int startIndex) {
        if(sum == target) {
            res.add(new ArrayList<>(path));
            return;
        }

        for(int i = startIndex; i < candidates.length; i++) {
            if(sum + candidates[i] > target) {
                break;
            }
            sum += candidates[i];
            path.add(candidates[i]);
            backTracking(candidates, target, sum, i);
            path.removeLast();
            sum -= candidates[i];

        }
    }
}
// @lc code=end

